let axios = require("axios");  //异步请求
let express = require('express');
let router = express.Router();
let utils = require('./utils');
let generateToken = utils.generateToken;
let User = require("../model/user");
let config = require('../config');

// 登录
router.post('/login', (req, res) => {
    console.log(req.body);
    let userInfo = req.body.userInfo;
    const queryString = `appid=${config.appId}&secret=${config.appSecret}&js_code=${req.body.code}&grant_type=authorization_code`;
    const wxAPI = `https://api.weixin.qq.com/sns/jscode2session?${queryString}`;

    axios.get(wxAPI)
        .then(function (response) {
            console.log(response.data);
            User.findOne({openId: response.data.openid}, (err, user) => {
                if(user){
                    return res.json({
                        token: generateToken({openId: response.data.openid})
                    })
                }else{
                    new User({
                        openId: response.data.openid,
                        nickName: userInfo.nickName,
                        avatarUrl: userInfo.avatarUrl
                    }).save()
                    return res.json({
                        token: generateToken({openId: response.data.openid})
                    })
                }
            })
        })
        .catch(function (error) {
            console.log(error);
    });   
});

module.exports = router;